<template>
  <div class="face_recognition">
    <div class="see">
      <div class="org">
        <img id="orgImg" src="images/xxm/xxm03.jpg" />
        <canvas id="orgCanvas" />
      </div>
      <div class="det">
        <img id="detImg" src="images/cp02.jpg" />
        <canvas id="detCanvas" />
      </div>
    </div>
  </div>
</template>

<script>
import * as faceapi from "face-api.js";
export default {
  name: "FaceRecognition",
  data() {
    return {
      nets: "ssdMobilenetv1",
      faceMatcher: null,
      orgImgEl: null,
      orgCanvasEl: null,
      detImgEl: null,
      detCanvasEl: null,
    };
  },
  
  mounted() {
    this.$nextTick(() => {
		//关键代码   初始化后进行人脸检测
		//由于识别是对比2张照片  所以先对1进行人脸检测  然后对对比图片进行人脸检测
      this.fnInit()
        .then(() => this.fnRun("org"))
        .then(() => this.fnRun("det"));
    });
  },
  methods: {
    // 初始化模型加载
    async fnInit() {
      await faceapi.nets[this.nets].loadFromUri("/models");
      await faceapi.loadFaceLandmarkModel("/models");
     //关键代码
	  await faceapi.loadFaceRecognitionModel("/models");//人脸识别
     
     this.options = new faceapi.SsdMobilenetv1Options({
            minConfidence: 0.5, // 0.1 ~ 0.9
      });
        
      // 节点对象
      this.orgImgEl = document.getElementById("orgImg");
      this.orgCanvasEl = document.getElementById("orgCanvas");
      this.detImgEl = document.getElementById("detImg");
      this.detCanvasEl = document.getElementById("detCanvas");
    },
    // 执行识别绘制
    async fnRun(el) {
      //el第一次为org 第二次为det
	  
	  //如果发现对比图片已经被检测过了  直接返回
	  if (!this.faceMatcher && el === "det") return;
      
	  //检测人脸
	  const fullFaceDescriptions = await faceapi
        .detectAllFaces(this[el + "ImgEl"], this.options)
        .withFaceLandmarks()//人脸特征（用来识别人脸）
        .withFaceDescriptors();//人脸描述（用来描述人脸的信息）
	
	  //未检测到人脸
      if (!fullFaceDescriptions.length) {
        this.faceMatcher = null;
        return;
      }
	  
      // 目标原图，转匹配矩阵
      if (el === "org") {
        this.faceMatcher = await new faceapi.FaceMatcher(fullFaceDescriptions);
      }
      // 识别图像绘制
	  //我们希望将画布与其显示尺寸匹配，
	  //我们可以使用faceapi.matchDimensions(canvas，displaySize)来做到这一点
      faceapi.matchDimensions(this[el + "CanvasEl"], this[el + "ImgEl"]);
     // 创建一个调整大小的检测变量，
	 //并将其设置为等于(faceapi.resizeResults(detections，displaySize)) ，
	 //以便将框调整为我们的脸部大小
	  const resizedResults = faceapi.resizeResults(
        fullFaceDescriptions,
        this[el + "ImgEl"]
      );
	  //遍历人像框 绘制内容
      resizedResults.forEach(({ detection, descriptor }) => {
        let best = this.faceMatcher.findBestMatch(descriptor);
        let label = el === "org" ? best["label"] : best.toString();
        new faceapi.draw.DrawBox(detection.box, { label }).draw(
          this[el + "CanvasEl"]
        );
      });
    },
   
  },
};
</script>

<style scoped>
.see .org,
.see .det {
  position: relative;
}
.see .org img,
.see .det img {
  max-width: 600px;
  max-height: 400px;
}
.see .org canvas,
.see .det canvas {
  position: absolute;
  top: 0;
  left: 0;
}
.option {
  padding-bottom: 20px;
}
.option div {
  padding: 10px;
  border-bottom: 2px #42b983 solid;
}
.option div label {
  margin-right: 20px;
}
</style>
